package reactor;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

/**
 * @ClassName EchoClient
 * @Description TODO
 * @Author leejiliang
 * @DateTime 2021/9/7 13:52
 * @Version 1.0
 */
public class EchoClient {
    int i = 0;

    public void start() throws IOException {

        // 初始换连接地址信息
        InetSocketAddress address = new InetSocketAddress("127.0.0.1", 9000);
        // 1、获取通道（channel）
        SocketChannel socketChannel = SocketChannel.open(address);
//		Logger.info("客户端连接成功");
        System.out.println("客户端连接成功");
        // 2、切换成非阻塞模式
        socketChannel.configureBlocking(false);
        //不断的自旋、等待连接完成，或者做一些其他的事情
        while (!socketChannel.finishConnect()) {
            System.out.println("自旋第: " + i++ + "次");
        }
        System.out.println("客户端启动成功！");

        //启动接受线程
        Processer processer = new Processer(socketChannel);
//		processer.run();
        // 客户端开始执行
        new Thread(processer).start();

    }

    static class Processer implements Runnable {
        final Selector selector;
        final SocketChannel channel;

        Processer(SocketChannel channel) throws IOException {
            // Reactor初始化, 初始化选择器
            selector = Selector.open();
            // 引用channel
            this.channel = channel;
            // 把channel注册到选择器中. 并关注channel的可读/可写事件
            channel.register(selector,
                    SelectionKey.OP_READ | SelectionKey.OP_WRITE);
        }

        public void run() {
            try {
                // 如果线程没有被标识中断, 会一直循环下去
                while (!Thread.interrupted()) {
                    // 等待选择器中有就绪事件, 这里关注的是channel的可读/可写就绪事件
                    selector.select();
                    // 获取就绪事件选择键集合
                    Set<SelectionKey> selected = selector.selectedKeys();
                    Iterator<SelectionKey> it = selected.iterator();
                    // 迭代就绪事件集合
                    while (it.hasNext()) {
                        SelectionKey sk = it.next();

                        // 如果是可写, 就是可以给服务端发送数据了
                        if (sk.isWritable()) {

                            // 初始化bufferN
                            ByteBuffer buffer = ByteBuffer.allocate(1024);

                            Scanner scanner = new Scanner(System.in);
                            System.out.println("请输入发送内容:");
                            if (scanner.hasNext()) {
                                SocketChannel socketChannel = (SocketChannel) sk.channel();
                                String next = scanner.next();
                                buffer.put((LocalDateTime.now() + " >>" + next).getBytes());
                                // buffer状态翻转, 从可写, 切换到可读
                                buffer.flip();
                                // 操作三：发送数据, 把数据从buffer中写入到channel, 然后发送给服务端
                                socketChannel.write(buffer);
                                // 清空buffer
                                buffer.clear();
                            }

                        }

                        // 如果是可读事件就绪, 说明服务端有发送数据过来,  需要接收处理
                        if (sk.isReadable()) {
                            // 若选择键的IO事件是“可读”事件,读取数据
                            SocketChannel socketChannel = (SocketChannel) sk.channel();

                            //读取数据
                            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                            int length = 0;
                            while ((length = socketChannel.read(byteBuffer)) > 0) {
                                // buffer切换到可读模式
                                byteBuffer.flip();
                                // 从buffer中读取数据, 并答应数据
                                System.out.println("server echo:" + new String(byteBuffer.array(), 0, length));
                                // 清空buffer
                                byteBuffer.clear();
                            }

                        }
                        //处理结束了, 这里不能关闭select key，需要重复使用
                        //selectionKey.cancel();
                    }
                    selected.clear();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        // 初始化客户端实例, 然后启动客户端
        new EchoClient().start();
    }
}
